import io
import os
import torch
import torchvision
import numpy as np
import pandas as pd
currentPath = os.getcwd()
dir_path = '/storage/emulated/0/Android/com.example.myapplication/'


# parent_directory = os.path.dirname(currentPath)
# path='save.pt'

# print(os.listdir(currentPath))
# path=r'file:\\android_asset\\save.pt'
# datapath=R'file:\\android_asset\\TEST.TXT'
###加载.pt文件
####数据处理

def pc_normalize(pc):
    centroid = np.mean(pc, axis=0)
    pc = pc - centroid
    m = np.max(np.sqrt(np.sum(pc ** 2, axis=1)))
    pc = pc / m
    return pc


sampledata = 3
datalength = 1200
pointNum = 1024  #####截取数据长度


####读取数据 1、读取大钱转化数据
###########2、去除零值
###########3、构造数据长度
def dealData(mydata):


    data11 = np.array(mydata)
    r1 = data11[:, 0:3] / 16384  ###加速度计数据转化
    r3 = (data11[:, 3:6] / 65.5) / 57.3  ###陀螺仪数据转化
    data33 = np.hstack((r1, r3))  ####加速度与陀螺仪数据拼接
    ##绘制轨迹
    vx = data33[:, 0]
    vy = data33[:, 1]
    vz = data33[:, 2]
    dx = vx + 0.5 * vx
    dy = vy + 0.5 * vy
    dz = vz + 0.5 * vz

    weiyix = np.cumsum(dx, 0)
    weiyiy = np.cumsum(dy, 0)
    weiyiz = np.cumsum(dz, 0)
    weiyix1 = weiyix[np.newaxis, :]
    weiyiy1 = weiyiy[np.newaxis, :]
    weiyiz1 = weiyiz[np.newaxis, :]

    yyy = np.zeros((1, weiyiy.shape[0]))
    weiyi = np.hstack((weiyix1.T, yyy.T, weiyiz1.T))  ###进入模型数据

    datalength = 1500
    ####增加数据长度 大于1024
    data2 = []  ###  当前数据长度
    # mydata=np.array(mydata)
    if (weiyi.shape[0] < sampledata) or (weiyi.shape[1] != 3):
        mydata = np.array([])  #####采集的数据小于3行,或者列数不等于3， 认为数据为不合格 置空
        var3 = torch.tensor(mydata)
    else:

        times = int(np.ceil(datalength / weiyi.shape[0]))  ##增加的倍数
        for U in range(times):
            data2.append(weiyi)
        data3 = np.array(data2)
        data4 = data3.reshape((-1, 3))
        data5=data4[0:1024,:]
        medata1 = pc_normalize(data5)  #####取最大值归一化
        ##数据格式转化
        var = torch.tensor(medata1)
        var1 = var.transpose(1, 0)
        var2 = var1.unsqueeze(0)
        var3 = var2.type(torch.float32)

    # ###进行预
    print('var3=',var3)
    return var3
# mydata = medata[~np.isnan(medata).any(axis=1)]          ####去除零值
# print('iiiiiiiii',mydata[0,:])
# print('iiiiiiiiiooooooo',(mydata.dtype))
# if (mydata.shape[0] < sampledata)or(mydata.shape[1]!=3):
#     print('#########')
#     mydata=np.array([])                                #####采集的数据小于3行,或者列数不等于3， 认为数据为不合格 置空
#     var3=torch.tensor(mydata)
# else:
#     print('*************')
#     mean = mydata.mean(axis=0)
#     std = mydata.std(axis=0)
#
#     standardized_data = (mydata - mean) / std
#     standardized_data = np.around(standardized_data, decimals=6)    ###数据归一化
#     medata1=pc_normalize(standardized_data)                                   #####取最大值归一化
#
#     data2 = []  ###  当前数据长度
#     times = int(np.ceil(datalength / medata1.shape[0]))  ##增加的倍数
#     for U in range(times):
#         data2.append(medata1)
#     data3 = np.array(data2)
#     data4 = data3.reshape((-1, 3))
#     print('receivedata   data4',data4.shape)
#     ##数据格式转化
#     var=torch.tensor(data4)
#     var1=var.transpose(1,0)
#     var2=var1.unsqueeze(0)
#     var3 = var2.type(torch.float32)
# ###进行预测
# return var3


def recognize(path, data):
    ptpath = path + '/save.pt'
    ###加载.pt文件

    with open(ptpath, 'rb') as f:
        buffer = io.BytesIO(f.read())

    model1 = torch.jit.load(buffer)

    data = dealData(data)

    if (data.numel() == 0):
        endFinal = -1
    else:
        traced_script_module, _ = model1(data)  ###数据进入模型 进行预测
        final = traced_script_module.data.max(1)[1]
        ###tensor 转化数组
        endFinal = final.numpy()
        if (endFinal == 0):
            endFinal = 4
        elif (endFinal == 1):
            endFinal = 3
        elif (endFinal == 2):
            endFinal = 1
        else:
            endFinal = 2
    return endFinal


def receive(receivedata, path):  #### 接收一个手势数据
    # time = receivedata[0]
    # print('receivedata   receivedata1',receivedata)
    # print('receivedata   str(receivedata)2',str(receivedata))
    # haha = str(receivedata).replace('[','').replace(']','')
    # print('receivedata1:',type(receivedata))
    # print('receivedata2:',(receivedata.dtype))
    # print('receivedata3:',receivedata)
    # haha2=receivedata.split('[')[-1].split(']')[0]
    # print('haha2:',haha2)
    with open(path, 'a') as file:
        # file.write(haha1 for haha1 in haha)
        file.write(receivedata + '\n')
    file.close()


def entry(inputdata, path):
    txtpath = path + '/save.txt'

    receive(inputdata, txtpath)
    Data = pd.read_csv(txtpath, header=None, index_col=None)
    out = Data.values  ###接收到的第七位结束位置
    outA = np.array(out)
    # print("python1 out",out)
    outB = []
    index = [i for i, row in enumerate(outA[:, -1]) if row == 60]  ####找出文件中最后一列等于60的索引 即所在行
    if len(index) > 0:

        if(outA[-1,-1]!=60):
            if (outA[index[0] - 1, -1] == 20 and (outA[index[-1] + 1, -1] == 10)):  ###判断等于60的开始索引上一条是否等于20,且等于60的终止索引等于10
                for i, data in enumerate(index):
                    outB.append(outA[data, :])
                    # print('python1outB', outB.shape)
                with open(txtpath, 'w') as file1:  ###手势数据取完,清空文件
                    # file.write(haha1 for haha1 in haha)
                    file1.write('\n')

    outC = np.array(outB)
    out = -1
    if outC.shape[0] > 0:
        out = recognize(path, outC)

    return (out)

    # out1=out[~np.isnan(Data).any(axis=1)]
    # return(out1)
